package org.robot.scm.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @Author : Awn create on 2024/4/12 14:55
 */
@Slf4j
public class NetImageTool {

    private static final OkHttpClient client = new OkHttpClient();


    public static boolean download(String imageUrl, String savePath) {
        Request request = new Request.Builder().url(imageUrl).build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
                return saveImageFromStream(inputStream, savePath);
            }
        } catch (IOException e) {
            log.error("image save fail, url : {}", imageUrl);
        }
        return false;
    }

    private static boolean saveImageFromStream(InputStream inputStream, String savePath) {
        try (OutputStream outputStream = Files.newOutputStream(Paths.get(savePath))) { // 创建输出流用于保存图片
            byte[] buffer = new byte[4096]; // 缓冲区大小可以根据需要进行调整
            int bytesRead; // 实际读取的字节数
            while ((bytesRead = inputStream.read(buffer)) != -1) { // 循环读取并写入输出流，直到读取完毕
                outputStream.write(buffer, 0, bytesRead); // 将读取的数据写入输出流，保存到本地文件
            }
            return true;
        } catch (IOException e) {
            log.error("save network image to local fail, error: {}", e.getMessage());
        }
        return false;
    }

}
